package com.hj.authority.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.fhs.trans.service.impl.TransService;
import com.hj.authority.dao.SysUserDao;
import com.hj.authority.domain.convert.SysUserConvert;
import com.hj.authority.domain.dto.SysUserDTO;
import com.hj.authority.domain.entity.SysUser;
import com.hj.authority.domain.enums.SuperAdminEnum;
import com.hj.authority.domain.enums.UserStatusEnum;
import com.hj.authority.service.SysMenuService;
import com.hj.authority.service.SysUserService;
import com.hj.exception.HjException;
import com.hj.mybatis.service.impl.BaseServiceImpl;
import com.hj.security.user.HjUserDetails;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author hj
 * @Date 2023/4/27
 * @Description: 用户管理
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUser> implements SysUserService {

    private final PasswordEncoder passwordEncoder;
    private final SysMenuService sysMenuService;
    //private final TransService transService;

    @Override
    public void save(SysUserDTO dto) {
        // 判断用户名是否存在
        SysUser user = baseMapper.getByUsername(dto.getUsername());
        if (null != user) {
            throw new HjException(403, "用户名已经存在");
        }
        // 密码加密
        dto.setPassword(passwordEncoder.encode(dto.getPassword()));
        SysUser entity = SysUserConvert.INSTANCE.dtoToEntity(dto);
        entity.setSuperAdmin(SuperAdminEnum.YES.getValue());
        // 保存用户
        baseMapper.insert(entity);
        // todo 赋予基本角色权限
    }

    @Override
    public SysUser getByUsername(String username) {
        SysUser byUsername = baseMapper.getByUsername(username);
        System.out.println(byUsername);
        return byUsername;
    }

    @Override
    public UserDetails getUserDetails(SysUser userEntity) {
        // 转换成UserDetail对象
        HjUserDetails userDetail = SysUserConvert.INSTANCE.convertDetail(userEntity);

        // 账号不可用
        if (userEntity.getStatus() == UserStatusEnum.DISABLE.getValue()) {
            userDetail.setEnabled(false);
        }
        // 用户权限列表
        Set<String> authoritySet = sysMenuService.getUserAuthority(userDetail);
        userDetail.setAuthoritySet(authoritySet);

        return userDetail;
    }



}
